package com.wocai.jrt.orgadmin.flow.action;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.flow.model.Flow;
import com.wocai.jrt.orgadmin.flow.model.FlowDetail;
import com.wocai.jrt.orgadmin.flow.model.FlowInstance;
import com.wocai.jrt.orgadmin.flow.model.FlowLog;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowDetailService;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowInstanceService;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowLogService;
import com.wocai.jrt.orgadmin.project.model.ProjectWithBLOBs;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 项目流程控制器
 * @author zhangyz
 * @date 2016-4-1 14:09:27
 */
@Controller
@RequestMapping("/projectFlow")
public class ProjectFlowAction extends GenericAction<Flow> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProjectFlowAction.class);
	
	@Inject
	private FlowInstanceService flowInstanceServiceImpl;
	@Inject
	private FlowLogService flowLogServiceImpl;
	@Inject
	private ProjectService projectServiceImpl;
	@Inject
	private FlowLogService projectLogImpl;
	@Inject
	private FlowDetailService projectDetailImpl;
	/**
	 * 流程控制url统一处理方法
	 */
	 @ResponseBody
     @RequestMapping("/proFlowUnitiveHandle")
     public JsonBean proFlowUnitiveHandle(@RequestBody FlowLog flowlog) {
    	JsonBean bean = new JsonBean();
    	try {
			if(StringUtils.isAnyBlank(flowlog.getEventId(),String.valueOf(flowlog.getResult()))){
				bean.setCode(0);
        		bean.setMessage("参数异常.");
        		return bean;
			}
			//流程处理
			bean = flowPublicController(flowlog);
			//邮箱消息发送
			//TODO:
		} catch (Exception e) {
			LOGGER.error("proFlowUnitiveHandle error, errorMsg=[{}].", e.getMessage());
		}
    	return bean;
	 }	
	 
	/**
     * 流程控制统一处理方法
     * @param step state
     * @return JsonBean
     */
    public JsonBean flowPublicController(FlowLog flowlog){
    	JsonBean bean = new JsonBean();
    	int state = flowlog.getState();
    	int step = flowlog.getStep();
    	Boolean flag = flowlog.getFlag();
    	Boolean isSugesst = flowlog.getIsSugesst();
    	try {
    		//获取项目的流程实例
        	FlowInstance fis =new FlowInstance();
        	String id = flowlog.getEventId();
        	fis.setEventId(id);
        	List<FlowInstance> fisList= flowInstanceServiceImpl.pagedList(fis);
        	if(fisList.size() != 1){
        		bean.setCode(0);
        		bean.setMessage("获取项目实例出错！");
        		LOGGER.info("flowPublicController find error :获取项目实例出错");
        		return bean;	
        	}
        	FlowInstance fistemp = flowInstanceServiceImpl.pagedList(fis).get(0);
        	fis=fistemp;
        	if(fistemp.getNowStep() != step){
        		bean.setCode(0);
        		bean.setMessage("项目流程状态错误！");
        		LOGGER.info("flowPublicController find error :项目流程状态错误");
        		return bean;
        	}
        	//是否改变流程当前状态
        	if(flag){
        		//当有审批意见且为同意
        		if(isSugesst && flowlog.getResult() == 1){
        			bean = flowInstanceStateUpdate(state,fistemp.getNowStep()+1,id,fis);
                //当有审批意见且为不同意
        		}else if(isSugesst &&  flowlog.getResult() == 2){
        			//当审批流程处于第二步时,否决直接进入录入状态,流程步骤返回第一步
        			if(fis.getNowStep() == 2){
        				bean = flowInstanceStateUpdate(1,1,id,fis);
        			//当审批流程不处于第二步时,否决直接进入已否决状态,流程步骤返回第二步
        			}else{
        				bean = flowInstanceStateUpdate(100,2,id,fis);
        				//更新当前所有流程日志状态为不在当前流程中
        				flowLogServiceImpl.updateLogState(id);
        			}
        		//当项目状态为已否决,则是重启立项,流程步骤返回第二布,状态变为申请立项	
        		}else if(flowlog.getState() == 100){
    				bean = flowInstanceStateUpdate(2,2,id,fis);
    			//其他提交审批流程直接进入下一流程
    			}else{
        			bean = flowInstanceStateUpdate(state,fistemp.getNowStep()+1,id,fis);
        		}
        	}
        	//是否生成流程日志
        	if(isSugesst){
        		FlowDetail  fd = new FlowDetail();
        		fd.setFlowId(fistemp.getFlowId());
        		fd.setStep(step);
        		List<FlowDetail> fdList = projectDetailImpl.pagedList(fd);
        		if(fdList.size() != 1){
            		bean.setCode(0);
            		bean.setMessage("获取流程定义出错！");
            		return bean;	
            	}
        		flowlog.setId(ObjectId.get().toString());
        		flowlog.setCreateTime(new Date());
        		flowlog.setEmployeeId(UserUtils.getUserId());
        		flowlog.setEmployeeName(UserUtils.getUser().getName());
        		flowlog.setStepName(fdList.get(0).getName());
        		flowlog.setOrgId(UserUtils.getOrgId());
        		LOGGER.info("flowPublicController save flowlog prams:[{}]",JSON.toJSONString(flowlog));
        		int resultp = projectLogImpl.save(flowlog);
        		if(resultp == 1){
            		bean.setCode(1);
            		bean.setMessage("流程日志生成成功!");
            	}else{
            		bean.setCode(0);
            		bean.setMessage("流程日志生成失败!");
            	}
        	}
		} catch (Exception e) {
			LOGGER.error("flowPublicController find error in Step=[{}],State =[{}], errorMsg=[{}].", step,state,e.getMessage());
			bean.setCode(0);
    		bean.setMessage(e.getMessage());
		}
        return bean;
    }
    
    /**
     * 更新项目和流程实例状态方法
     * @param int state,int step,String id,FlowInstance fis
     * @return JsonBean
     */
    public JsonBean flowInstanceStateUpdate(int state,int step,String id,FlowInstance fis){
    	JsonBean bean = new JsonBean();
    	try {
    		//提交审批,更新项目当前状态
    		ProjectWithBLOBs p = new ProjectWithBLOBs();
        	p.setState(state);
        	p.setId(id);
        	int result = projectServiceImpl.updateById(p);
        	//更新当前流程实例步骤
        	fis.setNowStep(step);
        	int results = flowInstanceServiceImpl.updateById(fis);
        	if(result == 1 && results == 1){
        		bean.setCode(1);
        		bean.setMessage("项目和流程实例更新成功!");
        	}else{
        		bean.setCode(0);
        		bean.setMessage("项目和流程实例更新失败!");
        	}
		} catch (Exception e) {
			LOGGER.error("flowInstanceStateUpdate find error in Step=[{}],State =[{}], errorMsg=[{}].", step,state,e.getMessage());
			bean.setCode(0);
    		bean.setMessage(e.getMessage());
		}
    	return bean;
    }
    
    /**
	 * 查看项目委员会个人表决意见
	 * 
	 * @param model
	 *            查询参数，携带ID
	 */
	@ResponseBody
	@RequestMapping("/queryVoteDetail")
	public JsonBean queryVoteDetail(@RequestBody FlowLog model) {
		JsonBean bean = new JsonBean();
		try {
			if(StringUtils.isAnyBlank(model.getEventId(),model.getStepName())){
				bean.setCode(0);
        		bean.setMessage("参数异常!");
        		return bean;
			}
			//获取委员会委员的个人决议意见
			 List<FlowLog> list = projectLogImpl.pagedList(model);
			 bean.setCode(1);
			 bean.setData(list);
     		 bean.setMessage("获取项目委员会个人表决意见成功!");
		} catch (Exception e) {
			bean.setCode(0);
			LOGGER.error("queryVote detail, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}
}
